package com.example.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {

    public  static  void  main(String[] args) throws IOException {


        //监听的端口
        final int port = 6666;
        //服务端（绑定端口）
        ServerSocket server = new ServerSocket(port);
        System.out.println("Server正在运行");
        while(true) {
            //等待客户端连接
            Socket socket = server.accept();
            //连接建立之后的操作
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while((len = inputStream.read(bytes)) != -1) {
                sb.append(new String(bytes, 0, len,"UTF-8"));
            }
            System.out.println("来息客户端的消息： " + sb.toString());

            //返回消息给客户端
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("服务器已收到消息！".getBytes("UTF-8"));

            inputStream.close();
            socket.close();
        }
    }
}
